package com.help10000.rms.ui.activitys.logins


import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewTreeObserver
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.amir.common.api.ApiContents
import com.amir.common.api.download.LoginPageEvent
import com.amir.common.mvp.presenter.IPresenter
import com.amir.common.mvp.view.IView
import com.amir.common.utils.AppManager
import com.amir.common.utils.DisplayUtil
import com.google.android.material.tabs.TabLayout
import com.help10000.rms.R
import com.help10000.rms.common.GlobalNetWorkObserver.cancelDialog
import com.help10000.rms.common.GlobalNetWorkObserver.displayNoNetworkDialog
import com.help10000.rms.ui.activitys.OpenUrlActivity
import com.help10000.rms.ui.base.BaseActivity
import com.help10000.rms.ui.fragments.LoginFragment
import com.help10000.rms.ui.utils.EventBusHelper
import com.help10000.rms.ui.utils.NetWorkUtil
import kotlinx.android.synthetic.main.activity_login.tablayout
import kotlinx.android.synthetic.main.activity_login.viewpager
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 登陆
 */
class LoginActivity : BaseActivity<IPresenter<IView>, IView>(), View.OnClickListener {
    var fragments = arrayListOf<Fragment>()
    override fun getlayoutId(): Int {
        return R.layout.activity_login
    }


    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        finish()
        startActivity(Intent(this, LoginActivity::class.java))

    }

    fun initFragment(reload: Boolean) {
        var content = intent.getStringExtra("push_content")
        viewpager.adapter = null
        fragments.clear()
        fragments.add(LoginFragment.newInstance(reload, content, false))
        fragments.add(LoginFragment.newInstance(reload, content, true))
        var adapter = object :
            FragmentPagerAdapter(supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            override fun getCount(): Int {
                return 2
            }

            override fun getItem(position: Int): Fragment {
                return fragments.get(position)
            }

        }
        viewpager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                tablayout.selectTab(tablayout.getTabAt(position))
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
        // 关键：设置预加载页数为2（确保两个Fragment都提前初始化视图）
        viewpager.offscreenPageLimit = 2 // 新增这行
        viewpager.adapter = adapter
        tablayout.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                if (tablayout.height > 0) {
                    var height = DisplayUtil.getDensityHeight(getViewContext());
                    var navHeight = tablayout.bottom
                    viewpager.layoutParams.height =
                        height - navHeight + DisplayUtil.getStatusBarHeight(getViewContext())
                    tablayout.viewTreeObserver.removeOnGlobalLayoutListener(this)
                }
            }
        })
    }

    override fun initView() {
        initFragment(false);
        // ShortcutBadger.removeCount(this)
    }

    override fun initData(savedInstanceState: Bundle?) {


        tablayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                viewpager.currentItem = tab!!.position
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })

    }

    override fun showLoading() {

    }

    override fun initListener() {
        super.initListener()
        //   et_phone.setText("625704")
        //  et_pwd.setText("123456")
        EventBusHelper.register(this)
        if (!NetWorkUtil.isNetWorkAvailable()) {
            displayNoNetworkDialog(
                AppManager.getAppManager().currentActivity()
            )
        } else {
            cancelDialog()
        }
    }


    override fun onDestroy() {
        EventBusHelper.unRegister(this)
        super.onDestroy()
//        LoginFragment.checkBoxState = false // 退出时重置
//        LoginFragment.stateListeners.clear() // 清空监听列表，彻底释放
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_userRule -> {
                OpenUrlActivity.startActivity(this, ApiContents.UserRuleUrl)
            }
            R.id.tv_userPrivacy -> {
                OpenUrlActivity.startActivity(this, ApiContents.UserPrivacyUrl)
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun loginPageEvent(loginPageEvent: LoginPageEvent) {
//        viewpager.currentItem = 0
    }


}

